import axios from "axios";
import { message } from 'antd';
import { BaseUrl } from './../utils/globalConst'

//axios请求拦截
axios.interceptors.request.use(
    config => {
        config.baseURL = BaseUrl;
        config.withCredentials = true; // 解决跨域产生的相关问题
        config.timeout = 6000;
        if ((config.method == 'post' || config.method == 'put') && config.data.format != 'JSON') {
            delete config.data.format;
            config.transformRequest = [function (data) {
                let ret = '';
                for (let it in data) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
                }
                return ret;
            }];
        }
        // config.headers['X-Api-Key'] = localStorage.getItem("X-Api-Key");
        // config.headers['X-User-Id'] = localStorage.getItem("X-User-Id");
        // config.headers['X-Client-Id'] = localStorage.getItem("X-Client-Id");
        config.headers = {
            'Accept': "application/json, text/plain, */*",
            'Content-Type': "application/x-www-form-urlencoded",
            'X-Api-Key': localStorage.getItem("X-Api-Key"),
            "X-User-Id": localStorage.getItem("X-User-Id"),
            "X-Client-Id": localStorage.getItem("browserFingerprint")
        };
        return config;
    },
    error => {
        console.log('error', error);
        return Promise.reject(error);
    }
)

/**
 * 响应的拦截
 */
axios.interceptors.response.use(
    res => {
        if (res.status) {
            switch (res.status) {
                case 500:
                    message.error("服务器异常");
                    break;
                case 404:
                    message.error("网络请求地址不存在");
                    break;
                case 200:
                    if (res.data.code == 4001) {
                        message.error("登录失效，请重新登录！");
                        window.open(`/#/login`, '_self');
                    }
                    break;
                case 400:
                    message.error("无效请求");
                    break;
                case 504:
                    message.error("请求超时");
                    break;
                default:
                    message.error('请求超时');
                    break;
            }
        }
        return res;
    },
    error => {
        return Promise.resolve(error.response);
    }
);

function checkStatus(response) {
    // loading
    // 如果http状态码正常，则直接返回数据
    if (
        response &&
        (response.status === 200 ||
            response.status === 304 ||
            response.status === 400)
    ) {
        return response.data;
        // 如果不需要除了data之外的数据，可以直接 return response.data
    }
    // 异常状态下，把错误信息返回去
    return {
        code: 404,
        msg: "请求出错"
    };
}

function messageTips(res) {
    if (res.code === 2002) {
        message.error(res.msg);
    } else if (res.code === 4010 || res.code === 404) {
        message.warning(res.msg);
    }
    return res;
};

export default {
    loginPost(options) {
        var data = options.params || {};
        return axios
            .post(options.block + options.url, data)
            .then(response => {
                return checkStatus(response);
            }).then(res => {
                return messageTips(res);
            }).catch(function (err) {
                message.error("哦豁，请求异常！！！");
                console.log(err);
            });
    },
    post(options) {
        var data = options.params || {};
        return axios
            .post(options.block + options.url, data)
            .then(response => {
                return checkStatus(response);
            }).then(res => {
                return messageTips(res);
            }).catch(function (err) {
                message.error("哦豁，请求异常！！！");
                console.log(err);
            });
    },
    put(options) {
        var data = options.params || {};
        return axios
            .put(options.block + options.url, data)
            .then(response => {
                return checkStatus(response);
            }).then(res => {
                return  messageTips(res);
            }).catch(function (err) {
                message.error("哦豁，请求异常！！！");
                console.log(err);
            });
    },
    get(options) {
        var data = options.params || {};
        return axios
            .get(options.block + options.url, { params: data })
            .then(response => {
                return checkStatus(response);
            }).then(res => {
                return messageTips(res);
            }).catch(function (err) {
                message.error("哦豁，请求异常！！！");
                console.log(err);
            });
    },
    delete(options) {
        var data = options.params || {};
        return axios
            .delete(options.block + options.url, { params: data })
            .then(response => {
                return checkStatus(response);
            }).then(res => {
                return options.isInfo == 1 ? res : messageTips(res);
            }).catch(function (err) {
                message.error("哦豁，请求异常！！！");
                console.log(err);
            });
    },
    deleteNoInfo(options) {
        options.isInfo = 1;//1代表没有提示消息
        this.delete(options);
    },
}
